package db

import (
	"database/sql"
	"github.com/Mrs4s/MiraiGo/message"
	_ "github.com/mattn/go-sqlite3"
	"path"
)

const (
	createNameTable = `
CREATE TABLE IF NOT EXISTS "name"
(
    "qqId" INTEGER PRIMARY KEY ,
    "nameString" TEXT NOT NULL 
);
`
	upsertNameTable = `
INSERT OR
REPLACE
INTO name (qqId, nameString)
VALUES (?, ?)
`
	selectNameTable = `
SELECT nameString
FROM "name"
where qqId = ?;
`

	deleteNameTable = `
DELETE
FROM name
WHERE qqId = ?;
`
)

var nameDb *sql.DB

func init() {
	nameDb, _ = sql.Open("sqlite3", path.Join(getExecutePath(), "name.db"))
}

func CreateNameDb() {
	_, _ = nameDb.Exec(createNameTable)
}

func SelectNameDbByGroup(groupMessage *message.GroupMessage) (name string) {
	qqId := groupMessage.Sender.Uin
	rows, err := nameDb.Query(selectNameTable, qqId)
	if err != nil {
		return groupMessage.Sender.DisplayName()
	}
	for rows.Next() {
		_ = rows.Scan(&name)
	}
	if name == "" {
		name = groupMessage.Sender.DisplayName()
	}
	return
}

func SelectNameDbByPrivate(privateMessage *message.PrivateMessage) (name string) {
	qqId := privateMessage.Sender.Uin
	rows, err := nameDb.Query(selectNameTable, qqId)
	if err != nil {
		return privateMessage.Sender.DisplayName()
	}
	for rows.Next() {
		_ = rows.Scan(&name)
	}
	if name == "" {
		name = privateMessage.Sender.DisplayName()
	}
	return
}

func UpsertNameDb(qqId int64, name string) {
	stmt, _ := nameDb.Prepare(upsertNameTable)
	_, _ = stmt.Exec(qqId, name)
}

func DeleteNameDb(qqId int64) {
	stmt, _ := nameDb.Prepare(deleteNameTable)
	_, _ = stmt.Exec(qqId)
}
